<template>
  <div class="padding-l-20 padding-r-20 padding-t-20 h-100 table-page">
    <filter-bar>
      <template slot="left-bar">
        <a-space>
            <a-input allowClear class="_searchInput position-r" placeholder="姓名"
                     v-model="searchForm.realName"/>
          <my-tree-select
            class="orgSelect"
            ref="myTree"
            :tree-data="orgTree"
            :value="treeValue"
            placeholder="请选择所属组织"
            :replaceFields="replaceFields"
            @selectChange="selectChange"
          />
            <a-select style="width: 180px" v-model="searchForm.enabled" allowClear placeholder="请选择状态" >
              <a-select-option value="0">
                 禁用
              </a-select-option>
              <a-select-option value="1">
                  启用
              </a-select-option>
            </a-select>
          <a-button
            class="nbcs-btn-search"
            @click="
              page.page = 1;
              getList(page, searchForm);
            "
            >查询
          </a-button>
          <a-button
            class="nbcs-btn-default"
            @click="
              clearObj(searchForm);
              treeValue = undefined;
              searchForm.enabled = undefined
            "
            >重置
          </a-button>
        </a-space>
      </template>

      <!-- <template slot="left-bar">
              <a-space>
                <a-input
                  class="_input"
                  placeholder="姓名"
                  @pressEnter="getList(page, searchForm)"
                  v-model="searchForm.realName"
                  allow-clear
                />
                <a-input
                  class="_input"
                  placeholder="登录账号"
                  @pressEnter="getList(page, searchForm)"
                  v-model="searchForm.username"
                  allow-clear
                />
                <a-select
                  class="select"
                  v-model="searchForm.enabled"
                  @change="getList(page, searchForm)"
                >
                  <a-select-option :key="item.key" v-for="item in enabledArr">{{
                    item.title
                  }}</a-select-option>
                </a-select>
                <a-button
                  @click="getList(page, searchForm)"
                  class="nbcs-btn nbcs-btn-primary position-r"
                  style="top: -1.6px"
                  >查询</a-button
                >
              </a-space>
            </template> -->
      <template slot="right-bar"> </template>
    </filter-bar>
    <interval-bg></interval-bg>
    <opt-bar>
      <div slot="left-bar">账号管理</div>
      <div slot="right-bar">
        <a-space>
          <a-button v-if="permission('sys:user:expireConfig')" @click="openExpire()" class="nbcs-btn nbcs-btn-default" style="top: -1.6px">过期时间设置 </a-button>
          <a-button v-if="permission('sys:user:validPwd')" @click="openUserPwd()" class="nbcs-btn nbcs-btn-default" style="top: -1.6px">密码有效期 </a-button>
<!--          <a-button v-if="permission('sys:user:add')" @click="edit(0)" class="nbcs-btn-green-bg" style="top: -1.6px">新增用户 </a-button>-->
        </a-space>
      </div>
    </opt-bar>
    <a-table bordered ref="_table" :columns="columns" :data-source="list" :pagination="pageConfig" rowKey="id" :loading="loading" :scroll="{ x: 800, y: tableHeight }">
      <template slot="roles" slot-scope="text">
        <a-tag v-for="(item, index) in text" :key="index">{{ item.name }}</a-tag>
      </template>
      <span slot="tags" slot-scope="text, record">
        <a-tag v-if="record.enabled" class="tag-green"> 正常 </a-tag>
        <a-tag v-else class="tag-red"> 锁定 </a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <a-space size="middle">
          <a @click="auth(record)">授权</a>
          <a-popconfirm @confirm="lock(record.enabled, record.id)">
            <span slot="title" v-if="record.enabled">确定锁定该账号吗？</span>
            <span slot="title" v-else>确定解锁该账号吗？</span>
            <a v-if="record.enabled">锁定</a>
            <a v-else>解锁</a>
          </a-popconfirm>
          <a-popconfirm title="确定要重置该运营人员的密码吗？" @confirm="reset(record.id)">
            <a>重置密码</a>
          </a-popconfirm>
          <a-popconfirm title="确定要重置该运营人员的登录错误次数吗？" @confirm="resetCount(record.id)">
            <a>重置登录错误次数</a>
          </a-popconfirm>
<!--          <a @click="edit(1, record)">编辑</a>-->
<!--          <a-popconfirm title="确定删除该用户吗？" @confirm="del(record)">-->
<!--            <a-icon slot="icon" type="question-circle-o" style="color: red" />-->
<!--            <a class="table-red-btn">删除</a>-->
<!--          </a-popconfirm>-->
        </a-space>
      </span>
    </a-table>
    <user-form @getList="getList(page, searchForm)"></user-form>
    <user-auth @refresh="getList(page, searchForm)"></user-auth>
    <user-pwd ref="userPwd"></user-pwd>
    <user-expire ref="userExpire"></user-expire>
  </div>
</template>

<script>
import OptBar from '@/layouts/OptBar';
import FilterBar from '@/layouts/FilterBar';
import IntervalBg from '@/layouts/IntervalBg';
import { list, del, resetPwd, lockUser, resetLoginErrCount } from '@/services/user';
import UserForm from './userForm';
import UserAuth from './userAuth';
import UserPwd from './userPwd';
import UserExpire from './userExpire';
import { cutDateSecond } from '@/utils/date';
import { getOrgByUser } from '@/services/org';
import { list2Tree } from '../../utils/common';
import { clearObj } from '../../utils/util';
import myTreeSelect from '../components/myTreeSelect';

export default {
  name: 'User',
  components: { OptBar, IntervalBg, FilterBar, UserForm, UserAuth, myTreeSelect, UserPwd, UserExpire },
  data() {
    return {
      tableHeight: 0,
      loading: false,
      orgArr: [],
      orgTree: [],
      treeValue: undefined,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id',
      },

      enabledArr: [
        { title: '账号状态（全部）', key: '' },
        { title: '正常', key: 1 },
        { title: '锁定', key: 0 },
      ],
      searchForm: {
        realName: '',
        username: '',
        enabled: undefined,
        findOrgId: '',
      },
      list: [],
      columns: [
        // {
        //   title: '序号',
        //   align: 'center',
        //   width: 60,
        //   dataIndex: 'id',
        //   customRender: (text, record, index) => {
        //     return (this.page.page - 1) * this.page.pageSize + index + 1;
        //   },
        // },
        { title: '姓名', dataIndex: 'realName' },
        { title: '账号', dataIndex: 'username' },
        { title: '手机号码', dataIndex: 'phone' },
        {
          title: '角色',
          dataIndex: 'roles',
          scopedSlots: { customRender: 'roles' },
        },
        {
          title: '状态',
          dataIndex: 'enabled',
          scopedSlots: { customRender: 'tags' },
        },
        {
          title: '所属组织',
          dataIndex: 'orgId',
          customRender: (text) => {
            let name = '';
            this.orgArr.forEach((item) => {
              if (item.id == text) name = item.name;
            });
            return name;
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          customRender: (text) => {
            return cutDateSecond(text);
          },
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          fixed: 'right',
          width: 380,
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageConfig: {
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['20', '30', '50'],
        total: 0,
        current: 1,
        showTotal: (total) => {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (page, pageSize) => {
          this.page.page = 1;
          this.page.pageSize = pageSize;
          this.getList(this.page, this.searchForm);
        },
        onChange: (page) => {
          this.page.page = page;
          this.getList(this.page, this.searchForm);
        },
      },
      page: {
        page: 1,
        pageSize: 20,
      },
      permissionsList: {
        query: false,
      },
    };
  },
  created() {
    Promise.all([getOrgByUser({isFilterSys: 1})]).then((res) => {
      if (res[0].data.code === 0) {
        this.orgArr = [...this.orgArr, ...res[0].data.data];
      }
      this.getList(this.page);
    });
    this.getOrgAll();
  },
  mounted() {
    this.tableHeight = document.querySelector('.table-page').clientHeight - 276;
  },
  methods: {
    clearObj,
    permission(name) {
      let permissions = this.$store.getters['account/permissions'];
      return permissions.filter((m) => m.operation.indexOf(name) >= 0).length > 0;
    },
    getList(page, params) {
      this.loading = true;
      list(
        Object.assign(
          {
            page: page.page,
            pageSize: page.pageSize,
          },
          params
        )
      ).then((res) => {
        this.loading = false;
        const { data } = res.data;
        this.list = data.list;
        this.pageConfig.current = data.page;
        this.pageConfig.total = data.totalRow;
      });
    },
    getOrgAll() {
      getOrgByUser({isFilterSys: 1}).then((res) => {
        if (res.data.code === 0) {
          this.orgTree = list2Tree(res.data.data);
        }
      });
    },
    selectChange(value) {
      this.searchForm.findOrgId = value;
      this.treeValue = value;
      this.page.page = 1;
      this.getList(this.page, this.searchForm);
    },
    del(obj) {
      del({ id: obj.id }).then((res) => {
        if (res.data.code === 0) {
          this.$message.success('删除成功');
          this.getList(this.page);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //重置密码
    reset(id) {
      resetPwd({ id: id }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success('重置成功');
        }
      });
    },
    resetCount(id) {
      resetLoginErrCount({ id: id }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success('重置成功');
        }
      });
    },
    //解锁/锁定用户
    lock(enabled, id) {
      let flag = enabled ? 0 : 1;
      console.log(flag);
      lockUser({
        enabled: flag,
        id: id,
      }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success('操作成功');
          this.getList(this.page);
        }
      });
    },
    //添加/编辑
    edit(action, data = {}) {
      this.$bus.$emit('userVisible', {
        state: true,
        action: action,
        data: data,
      });
    },
    //授权
    auth(data) {
      this.$bus.$emit('userAuthVisible', { state: true, data: data.id });
    },
    openUserPwd() {
      this.$refs['userPwd'].changeForm(true);
    },
    openExpire() {
      this.$refs['userExpire'].changeForm(true);
    },
  },
};
</script>

<style lang="less" scoped>
.select {
  width: 170px;

  /deep/ .ant-select-selection {
    width: 100%;
  }
}

._input {
  width: 180px;
}

.orgSelect {
  width: 170px;
}

.table-page {
  .ant-table-wrapper {
    max-height: calc(100% - 150px);
  }
}
</style>
